$(function () {
  const layer = layui.layer
  const $image = $('#image')
  const options = {
    aspectRation: 1,
    preview: '.img-preview',
  }

  $image.cropper(options)

  $('#btnChoose').on('click', function () {
    $('#file').click()

    $('#file').on('change', function (e) {
      let files = e.target.files[0]
      console.log(files)

      var newImage = URL.createObjectURL(files)

      $image.cropper('destroy').attr('src', newImage).cropper(options)
    })
  })

  $('#upImage').on('click', function (e) {
    let dataUrl = $image
      .cropper('getCroppedCanvas', {
        // 创建一个 Canvas 画布
        width: 100,
        height: 100,
      })
      .toDataURL('image/png')
    console.log(dataUrl)

    $.ajax({
      method: 'POST',
      url: '/my/update/avatar',
      data: {
        avatar: dataUrl,
      },
      success: function (res) {
        if (res.status !== 0) return layer.msg('更新失败')
        layer.msg('更新成功！')

        window.parent.getInfouser()
      },
    })
  })
})
